package com.ca.ridersclubapplication;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.data.entity.LongEntity;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.ClubRequester;
import com.ca.ridersclubapplication.request.PaperRequester;
import com.ca.ridersclubapplication.request.dto.AccountDto;
import com.ca.ridersclubapplication.request.AccountRequester;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.dto.ClubDto;
import com.ca.ridersclubapplication.request.dto.PaperCardDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.adapter.PaperAdapter;
import com.ca.ridersclubapplication.data.bean.ClubInfo;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ca.ridersclubapplication.view.bar.AccountTitleBar;
import com.ca.ridersclubapplication.view.button.CountValueButton;
import com.ca.ridersclubapplication.view.card.AccountCard;
import com.ca.ridersclubapplication.view.list.FollowClubListView;

import java.util.ArrayList;
import java.util.List;

public class AccountActivity extends ImmersiveActivity {

    private Long accountId;


    private Long startId =  Long.MAX_VALUE;
    private boolean canRequest = true;


    private ConstraintLayout parentCL;

    private ConstraintLayout mainTitleCL;
    private AccountTitleBar accountTitleBar;

    private NestedScrollView nsv;

    private AccountCard accountCard;

    private CountValueButton paperButton;
    private CountValueButton followButton;
    private CountValueButton fansButton;

    //  回调视图，数据变化后更新视图显示
    private CallbackView paperCbv;
    private CallbackView followCbv;
    private CallbackView fansCbv;

    private FollowClubListView followClubListView;
    private boolean isFollow = false;


    private RecyclerView rv;
    private final PaperAdapter adapter = new PaperAdapter(this, null);
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);

        initData();

        initView();

        initListener();

        loadData();
    }

    /**
     * 初始化数据，从Intent中获取
     */
    private void initData() {
        accountId = getIntent().getLongExtra("accountId", 0L);
        if (accountId == 0) {
            finishAfterTransition();
        }
    }

    /**
     *  初始化视图
     */
    private void initView() {

        parentCL = findViewById(R.id.cl_parent);

        //  顶部的账号标题栏
        mainTitleCL = findViewById(R.id.cl_mainTitle);
        accountTitleBar = findViewById(R.id.bar_accountTitle);

        //  滑动容器
        nsv = findViewById(R.id.nsv);

        //  顶部的账号卡片
        accountCard = findViewById(R.id.card_account);
        accountCard.genderCL.setVisibility(View.GONE);

        //  小飞机
        if (DataHandler.getToken(this).getId().equals(accountId)) {
            accountTitleBar.chatView.setVisibility(View.GONE);
        }

        //  如果查看的账号与登录的账号一致，则隐藏标题栏和账号卡片上的关注按钮
        if (accountId.equals(DataHandler.getToken(this).getId())) {
            accountTitleBar.followView.setVisibility(View.GONE);
        }

        //  数据按钮
        paperButton = findViewById(R.id.btn_paperCount);
        followButton = findViewById(R.id.btn_followCount);
        fansButton = findViewById(R.id.btn_fansCount);

        //  关注车友会列表卡片
        followClubListView = findViewById(R.id.lv_followClub);
        followClubListView.setActivity(this);

        //  动态列表
        rv = findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        rv.setAdapter(adapter);
        rv.setNestedScrollingEnabled(false);

        //  进度条
        progressBar = findViewById(R.id.bar_progress);

        //  设置标题栏头像、名字Alpha
        accountTitleBar.headerView.setAlpha(0f);
        accountTitleBar.nameView.setAlpha(0f);
        mainTitleCL.setElevation(0f);


        //  回调视图
        paperCbv = new CallbackView() {
            @Override
            public void update() {
                Handleable data = DataHandler.getData("PaperCount:" + accountId);
                if (data instanceof LongEntity) {
                    LongEntity count = (LongEntity) data;
                    paperButton.setValue(paperButton.getValue() + count.getValue());
                }
            }
        };
        DataHandler.putView("PaperCount:" + accountId, paperCbv);

        followCbv = new CallbackView() {
            @Override
            public void update() {
                Handleable data = DataHandler.getData("FollowCount:" + accountId);
                if (data instanceof LongEntity) {
                    LongEntity count = (LongEntity) data;
                    followButton.setValue(followButton.getValue() + count.getValue());
                }
            }
        };
        DataHandler.putView("FollowCount:" + accountId, followCbv);

        fansCbv = new CallbackView() {
            @Override
            public void update() {
                Handleable data = DataHandler.getData("FansCount:" + accountId);
                if (data instanceof LongEntity) {
                    LongEntity count = (LongEntity) data;
                    fansButton.setValue(fansButton.getValue() + count.getValue());
                }
            }
        };
        DataHandler.putView("FansCount:" + accountId, fansCbv);
    }

    /**
     * 设置事件监听
     */
    private void initListener() {

        //  监听NSV滑动事件，调整标题栏样式（隐藏、显示头像、海拔等）
        nsv.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> accountCard.post(() -> {

            if (scrollY == 0) {
                accountTitleBar.headerView.setAlpha(0f);
                accountTitleBar.nameView.setAlpha(0f);
                mainTitleCL.setElevation(0f);
                return;
            }

            float ratio = 1.0f * scrollY / (accountCard.getHeight() + 64);
            float alpha = ratio > 1 ? 1 : ratio;
            accountTitleBar.headerView.setAlpha(alpha);
            accountTitleBar.nameView.setAlpha(alpha);
            mainTitleCL.setElevation(ratio > 1 ? 4 : ratio * 4);

            //  滑动到底部则加载新的文章数据
            if (!nsv.canScrollVertically(1)) {
                requestPaper();
            }
        }));

        //  返回按钮
        accountTitleBar.backView.setOnClickListener(v -> {
            finishAfterTransition();
        });

        //  关注按钮点击事件
        View.OnClickListener followBCL = v -> {
            if (DataHandler.isLogin(this)) {

                if (isFollow) {
                    AccountRequester.deleteFollow(this, accountId, new AfterExecutor<String>() {
                        @Override
                        public void execute(Result<String> result) {
                            if (result.isSuccess()) {
                                //  取关成功，粉丝数据 - 1
                                fansButton.setValue(fansButton.getValue() - 1);
                                Button followButton = accountTitleBar.followView;
                                followButton.setText("关注");
                                followButton.setBackgroundColor(getResources().getColor(R.color.danger));
                                followButton.setTextColor(getResources().getColor(R.color.white_text));
                                isFollow = false;
                            }
                            else {
                                Toast.makeText(AccountActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
                else {
                    AccountRequester.addFollow(this, accountId, new AfterExecutor<String>() {
                        @Override
                        public void execute(Result<String> result) {
                            if (result.isSuccess()) {
                                //  关注成功，粉丝数据 + 1
                                fansButton.setValue(fansButton.getValue() + 1);
                                Button followButton = accountTitleBar.followView;
                                followButton.setText("取关");
                                followButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                                followButton.setTextColor(getResources().getColor(R.color.secondary_text));
                                isFollow = true;
                            }
                            else {
                                Toast.makeText(AccountActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }
        };
        accountTitleBar.followView.setOnClickListener(followBCL);

        //  小飞机按钮
        accountTitleBar.chatView.setOnClickListener(v -> {
            //  启动聊天Activity
            Intent intent = new Intent(this, ChatActivity.class);
            intent.putExtra("targetId", accountId);
            startActivity(intent);
        });

        //  数据按钮点击事件
        followButton.setOnClickListener(v -> {
            Intent intent = new Intent(this, AccountListActivity.class);
            intent.putExtra("accountId", accountId);
            intent.putExtra("type", "followList");
            startActivity(intent);
        });

        fansButton.setOnClickListener(v -> {
            Intent intent = new Intent(this, AccountListActivity.class);
            intent.putExtra("accountId", accountId);
            intent.putExtra("type", "fansList");
            startActivity(intent);
        });

        followClubListView.setOnClickListener(v -> {
            Intent intent = new Intent(this, ClubListActivity.class);
            intent.putExtra("classify", "follow:" + accountId);
            startActivity(intent);
        });
    }

    /**
     * 加载数据，一般请求网络数据
     */
    private void loadData() {

        //  请求账号数据
        AccountRequester.getAccount(this, accountId, new AfterExecutor<AccountDto>() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            public void execute(Result<AccountDto> result) {

                if (result.isSuccess()) {
                    AccountDto accountDto = result.getData();
                    accountTitleBar.setName(accountDto.getNickname());
                    accountCard.setName(accountDto.getNickname());
                    accountCard.setGrade(String.valueOf(accountDto.getGrade()));
                    accountCard.setGradeCurrentValue(accountDto.getCurrentGradeValue());
                    accountCard.setGradeMaxValue(accountDto.getMaxGradeValue());
                    if (accountDto.getProfile() != null && accountDto.getProfile().trim().isEmpty()) {
                        accountCard.profileView.setVisibility(View.GONE);
                    }
                    else {
                        accountCard.profileView.setVisibility(View.VISIBLE);
                        accountCard.profileView.setText(accountDto.getProfile());
                    }
                    String gender = accountDto.getGender();
                    if (gender.equals("男")) {
                        accountCard.genderTV.setText("男");
                        accountCard.genderIV.setImageDrawable(getResources().getDrawable(R.drawable.ic_man));
                        accountCard.genderCL.setBackground(getResources().getDrawable(R.drawable.gender_man_bg));
                        accountCard.genderCL.setVisibility(View.VISIBLE);
                    }
                    else if (gender.equals("女")) {
                        accountCard.genderTV.setText("女");
                        accountCard.genderIV.setImageDrawable(getResources().getDrawable(R.drawable.ic_femal));
                        accountCard.genderCL.setBackground(getResources().getDrawable(R.drawable.gender_femal_bg));
                        accountCard.genderCL.setVisibility(View.VISIBLE);
                    }
                    else {
                        accountCard.genderCL.setVisibility(View.GONE);
                    }
                    paperButton.setValue(accountDto.getPaperCount());
                    followButton.setValue(accountDto.getFollowCount());
                    fansButton.setValue(accountDto.getFansCount());
                }
            }
        });

        //  请求头像
        accountTitleBar.setHeaderUrl(FileRequester.HEADER_BY_ID_BASE_URL + accountId);
        accountCard.setHeaderUrl(FileRequester.HEADER_BY_ID_BASE_URL + accountId);

        //  请求是否关注数据
        if (!accountId.equals(DataHandler.getToken(this).getId())) {
            AccountRequester.isFollow(this, accountId, new AfterExecutor<Boolean>() {
                @Override
                public void execute(Result<Boolean> result) {
                    Boolean data = result.getData();
                    if (result.isSuccess() && data != null) {
                        isFollow = data;
                        if (isFollow) {
                            Button followButton = accountTitleBar.followView;
                            followButton.setText("取关");
                            followButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                            followButton.setTextColor(getResources().getColor(R.color.secondary_text));
                        }
                        else {
                            Button followButton = accountTitleBar.followView;
                            followButton.setText("关注");
                            followButton.setBackgroundColor(getResources().getColor(R.color.danger));
                            followButton.setTextColor(getResources().getColor(R.color.white_text));
                        }
                    }
                }
            });
        }

        //  请求账号关注车友圈数据
        ClubRequester.listFollowClub(this, accountId, new AfterExecutor<List<ClubDto>>() {
            @Override
            public void execute(Result<List<ClubDto>> result) {
                if (result.isSuccess()) {
                    //  请求成功，设置数据
                    List<ClubDto> data = result.getData();
                    List<ClubInfo> infoList = new ArrayList<>();
                    for (ClubDto dto : data) {
                        infoList.add(new ClubInfo(
                                dto.getId(),
                                FileRequester.CLUB_IMAGE_1_1_BASE_URL + dto.getId(),
                                dto.getName(),
                                dto.getPaperCount()
                        ));
                    }

                    followClubListView.setInfoList(infoList);
                }
            }
        });

        //  请求动态列表（文章）数据
        requestPaper();
    }

    private synchronized void requestPaper() {
        if (canRequest) {
            canRequest = false;
            //  显示加载动画
            progressBar.setVisibility(View.VISIBLE);
            PaperRequester.listPaperByAccountId(this, accountId, startId, new AfterExecutor<List<PaperCardDto>>() {
                @Override
                public void execute(Result<List<PaperCardDto>> result) {
                    if (result.isSuccess()) {
                        //  请求成功，设置数据
                        List<PaperCardDto> data = result.getData();
                        //  追加数据
                        adapter.appendList(data);

                        //  设置startId
                        if (data.size() > 0) {
                            startId = data.get(data.size() - 1).getId();
                        }

                        //  关闭加载动画
                        progressBar.setVisibility(View.GONE);
                        canRequest = true;
                    }
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        DataHandler.removeView("PaperCount:" + accountId, paperCbv);
        DataHandler.removeView("FollowCount:" + accountId, followCbv);
        DataHandler.removeView("FansCount:" + accountId, fansCbv);
    }
}